package com.zut.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.zut.pojo.Food;
import com.zut.pojo.PageInfo;
import com.zut.service.FoodService;
import com.zut.service.impl.FoodServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张晨
 * @date 2024/9/13 10:46
 * @desc
 */
@WebServlet("/food")
public class FoodController extends HttpServlet {
    private FoodService foodService = new FoodServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getParameter("op");
        if (StringUtils.isEmpty(op)){
            resp.getWriter().write("参数错误");
            return;
        }

        switch (op){
            case "sel":
                selFood(req,resp);
                break;
            case "add":
                addFood(req,resp);
                break;
            case "del":
                delFood(req,resp);
                break;
            case "upd":
                updFood(req,resp);
                break;
        }
        
    }

    private void updFood(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void delFood(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void addFood(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void selFood(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // http://localhost:8080/food?op=sel&categoryId=30&shopId=263
        Integer categoryId = Integer.parseInt(req.getParameter("categoryId"));
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        String foodName = req.getParameter("foodName");
        String status = req.getParameter("status");

        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");

        if(StringUtils.isEmpty(currentPage)){
            currentPage = "1";
        }
        if(StringUtils.isEmpty(pageSize)){
            pageSize = "5";
        }

        Food food = new Food();
        if (!StringUtils.isEmpty(foodName)){
            food.setFoodName(foodName);
        }
        if (!StringUtils.isEmpty(status)){
            food.setStatus(Integer.parseInt(status));
        }
        food.setCategoryId(categoryId);
        food.setShopId(shopId);

        PageInfo result =  foodService.selectCond(food,Integer.parseInt(currentPage),Integer.parseInt(pageSize));

        String jsonString = JSON.toJSONString(result);

        resp.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
